<template>
  <div class="ram-manage">
    <div class="section-container">
      <div class="section-title">
        RAM用户管理
      </div>
      <div class="section-description">
        <i class="iconfont">&#xe60e;</i>
        <p>
          RAM 用户是 RAM 中的一种实体身份，代表需要访问后台的人员或应用程序。通过创建 RAM 用户并授权，RAM 用户就可以访问有权限的云资源。
          <br />
          如您想对于 RAM 用户的使用情况做检测和治理，可移步身份权限治理检测，该服务免费使用。
        </p>
      </div>
      <div class="section-actions">
        <div class="actions-left">
          <el-button type="primary" @click="ramMemberDialog = true">添加用户</el-button>
        </div>
      </div>
      <RuifoxTable :loading="tableLoading" :default-index="true" :default-checkbox="true" v-model:tableData="tableData" v-model:fieldList="fieldList">
        <template #default-checkbox="{ element }">
          <div class="table-div-check">
            <el-checkbox class="unmover" v-model="element.checked" @change="handleCheckTable(element.id)" />
          </div>
        </template>
        <template #state="{ element }">
          <el-switch
            v-model="element.state"
            :loading="banLoading && element.id === curBan"
            @click="handleBanRamMember(element.id)"
            :before-change="() => beforeBan(element)"
            :active-value="0"
            :inactive-value="1"
            inline-prompt
            active-text="是"
            inactive-text="否"
          />
        </template>
        <template #avatar="{ element }">
          <div class="img-box">
            <div class="no-avatar" v-if="!element.avatar">
              <p>{{ element.name[0] }}</p>
            </div>
            <div v-else class="has-avatar">
              <img :src="element.avatar" alt="" />
            </div>
          </div>
        </template>
        <template #options="{ element }">
          <div class="table-td-option">
            <el-button type="primary" link @click="handleEditUser(element)">编辑用户</el-button>
            <el-button type="primary" link @click="handleEditPermission(element)">权限分配</el-button>
            <el-button type="primary" link @click="handleDelete(element)">删除</el-button>
          </div>
        </template>
      </RuifoxTable>
      <PaginationView
          :total="queryData.total"
          :pageSize="queryData.pageSize"
          :currentPage="queryData.currentPage"
          :allChoose="isAllChooseBtn"
          :pageChoose="isPageChooseBtn"
          :checkedNum="checkedNum"
          :options="batchOptions"
          @changeSize="handleSizeChange"
          @currentChange="handleCurrentChange"
          @changePageChoose="handlePageChoose"
          @changeAllChoose="handleAllChoose"
          @invertChoose="handleInvertChoose"
          @checkOption="handleBatch"
          @refreshList="getTableData"
          @cancelChoose="handleResetPagination"
        />
    </div>
    <!-- ram用户添加/编辑 -->
    <el-dialog v-model="ramMemberDialog" :title="ramMemberForm.id ? '编辑RAM成员' : '添加RAM成员'" width="30%" align-center @close="ramDialogClose">
      <el-form ref="ramMemberFormRef" :rules="ramMemberFormRules" :model="ramMemberForm" label-width="80px" label-position="right">
        <el-form-item label="用户名称" prop="name">
          <el-input v-model="ramMemberForm.name"></el-input>
        </el-form-item>
        <el-form-item label="登录账号" prop="account">
          <el-input v-model="ramMemberForm.account"></el-input>
        </el-form-item>
        <!-- <el-form-item label="所属角色：" prop="roleIds">
          <el-select v-model="ramMemberForm.roleIds" class="m-2" placeholder="请选择所属角色" multiple>
            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="过期时间" prop="validTime">
          <el-date-picker v-model="ramMemberForm.validTime" value-format="x" type="datetime" placeholder="请选择过期时间" />
        </el-form-item>
        <el-form-item label="头像设置" prop="avatar">
          <el-input v-model="ramMemberForm.avatar"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitRamMember">确认</el-button>
          <el-button @click="ramMemberDialog = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- ram菜单权限分配 -->
    <el-dialog v-model="permissionDialog" title="用户权限" width="20%" @close="resetDisable">
      <p style="margin-bottom: 10px; font-size: 12px">用于单独分配菜单，禁用选项为所属角色所拥有的菜单</p>
      <el-scrollbar height="400px" style="width: 100%">
        <el-tree ref="permissionRef" :data="permissionTree" :props="permissionTreeProps" default-expand-all show-checkbox :indent="10" node-key="id" style="width: 100%"></el-tree>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialog = false">取消</el-button>
          <el-button type="primary" @click="submitPermission">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
/* eslint-disable */
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { getUserRoutes } from '@/api/user'
import { getRamUser, insertRamUser, updateRamUser, banRamUser, deleteRamUser, batchDeleteRamUser } from '@/api/ramUser'
import { getMenuByUserId, getRoleList, getRoleCratedBySelf } from '@/api/role'
import { getRoleMenusByUserId, bindUserMenu } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { tableList as mixTable, createTreeData } from '@ruifox-cms/utils'

const fieldList = ref([
  {
    title: 'ID',
    name: 'id',
    width: 60
  },
  {
    title: '用户名称',
    name: 'name'
  },
  {
    title: '用户账号',
    name: 'account'
  },
  {
    title: '是否启用',
    name: 'state'
  },
  {
    title: '头像',
    name: 'avatar'
  },
  {
    title: '操作',
    width: 240,
    fixed: 'right',
    name: 'options'
  }
])
const store = useStore()
const userInfo = computed(() => store.getters.userInfo)
// 获取角色列表（非系统用户只能查看自己）
const roleList = ref([])
const _getRoleList = async () => {
  let res
  if (userInfo.value.isSystem) {
    res = await getRoleList()
  } else {
    res = await getRoleCratedBySelf()
  }
  if (res.code === 20000) {
    roleList.value = res.data
  }
}
_getRoleList()

// 获取用户的权限
const permissionTree = ref([])
const permissionTreeProps = ref({
  children: 'children',
  label: function (data) {
    return data.title
  }
})
const handleGetPermission = async () => {
  let res = await getUserRoutes()
  if (res.code === 20000) {
    permissionTree.value = createTreeData(res.data)
  }
}
handleGetPermission()

// 获取指定账号下的RAM用户
const {
  queryData,
  tableData,
  tableLoading,
  checkedNum,
  isAllChooseBtn,
  isPageChooseBtn,
  isAllSearch,
  checkedList,
  getTableData,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleResetPagination
} = mixTable({
  getListApi: getRamUser
})
const defaultRamQuery = {
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pid: userInfo.value.id
}
Object.assign(queryData, defaultRamQuery)

// ram用户添加
const defaultRamMemberForm = reactive({
  id: null,
  account: '',
  avatar: '',
  name: '',
  menuIds: [],
  authIds: [],
  isUseInterface: false
})
const ramMemberDialog = ref(false)
const ramMemberFormRef = ref(null)
const ramMemberForm = ref(Object.assign({}, defaultRamMemberForm))
const ramMemberFormRules = reactive({
  account: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入用户名称', trigger: 'blur' }]
})

// 编辑ram用户
const ramPermissionRef = ref(null)
const handleEditUser = data => {
  ramMemberForm.value = Object.assign({}, data)
  ramMemberDialog.value = true
}

// 提交
const submitRamMember = () => {
  ramMemberFormRef.value.validate(valid => {
    if (valid) {
      if (ramMemberForm.value.id) {
        updateRamUser(ramMemberForm.value).then(res => {
          if (res.code === 20000) {
            ElMessage({
              showClose: true,
              message: '修改成功',
              type: 'success'
            })
            getTableData()
            ramMemberDialog.value = false
          }
        })
      } else {
        const menuIds = ramPermissionRef.value.getCheckedKeys()
        ramMemberForm.value.menuIds = menuIds
        insertRamUser(ramMemberForm.value).then(res => {
          if (res.code === 20000) {
            ElMessage({
              showClose: true,
              message: '添加成功',
              type: 'success'
            })
            getTableData()
            ramMemberDialog.value = false
          }
        })
      }
    }
  })
}

// 删除ram用户
const handleDelete = row => {
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否删除所选成员？</p><span style="font-size: 14px;color: #FF5240;">删除后成员将被移除</span></div>', '删除确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(() => {
    deleteRamUser({ id: row.id }).then(() => {
      getTableData()
      ElMessage({
        showClose: true,
        message: '删除成功',
        type: 'success'
      })
    })
  })
}

// 批量删除ram用户
const handleBatchDelete = () => {
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否批量删除所选RAM成员？</p><span style="font-size: 14px;color: #FF5240;">删除后成员将被移除</span></div>', '删除确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(() => {
    batchDeleteRamUser({ ids: checkedList.value, isAllChoose: isAllSearch.value }).then(() => {
      getTableData()
      ElMessage({
        showClose: true,
        message: '删除成功',
        type: 'success'
      })
    })
  })
}

// 禁用ram用户
const banLoading = ref(false)
const curBan = ref('')
const handleBanRamMember = id => {
  banLoading.value = true
  curBan.value = id
}
const beforeBan = data => {
  return new Promise(resolve => {
    const msg = data.state ? '启用成功' : '禁用成功'
    const result = {
      id: data.id,
      isBan: data.state ? false : true
    }
    banRamUser(result).then(res => {
      ElMessage({
        showClose: true,
        message: msg,
        type: 'success'
      })
      if (res.code === 20000) {
        banLoading.value = false
        resolve(true)
      }
    })
  })
}

const ramDialogClose = () => {
  ramMemberFormRef.value?.resetFields()
  ramMemberForm.value = Object.assign({}, defaultRamMemberForm)
}

// 编辑用户菜单权限
const permissionRef = ref(null)
const permissionForm = ref({})
const permissionDialog = ref(false)
const permissionLoading = ref(false)
const disablePermission = ref([])
const handleEditPermission = async row => {
  permissionDialog.value = true
  permissionLoading.value = true
  permissionForm.value.userId = row.id
  const res = await getMenuByUserId({ userId: row.id })
  let menuIds = []
  if (res.code === 20000) {
    menuIds = res.data ? res.data.map(item => item.id) : []
  }
  const res2 = await getRoleMenusByUserId({ userId: row.id })
  if (res2.code === 20000) {
    disablePermission.value = res2.data ? res2.data.map(item => item.id) : []
  }
  const checked = [...menuIds, ...disablePermission.value]
  permissionRef.value.setCheckedKeys(checked)
  permissionLoading.value = false
}

// 更新用户菜单权限
const submitPermission = () => {
  const menusIds = permissionRef.value.getCheckedKeys()
  permissionForm.value.menuIds = menusIds
  bindUserMenu(permissionForm.value).then(res => {
    if (res.code === 20000) {
      ElMessage({
        showClose: true,
        message: '修改成功',
        type: 'success'
      })
      permissionDialog.value = false
    }
  })
}

const resetDisable = () => {
  disablePermission.value = []
}

// 勾选用户
const handleCheckTable = id => {
  if (checkedList.value.includes(id)) {
    checkedList.value = checkedList.value.filter(item => item != id)
  } else {
    checkedList.value.push(id)
  }
}

// 批量操作
const batchOptions = ref([
  {
    name: '删除',
    icon: '&#xe718;',
    value: 'delete'
  }
])
const handleBatch = (val) => {
  if(val === 'delete'){
    handleBatchDelete()
  }
}

onMounted(() => {
  // 获取用户的RAM用户
  getTableData()
})
</script>

<style lang="scss" scoped>
.ram-manage {
  .img-box {
    height: 50px;
    width: 50px;
    border-radius: 50%;
    overflow: hidden;
    position: relative;
    .no-avatar {
      display: flex;
      background-color: $mainColor;
      height: 100%;
      width: 100%;
      justify-content: center;
      align-items: center;
      p {
        color: #fff;
        font-size: 32px;
      }
    }
    .has-avatar {
      height: 100%;
      width: 100%;
      img {
        height: 100%;
        width: 100%;
      }
    }
  }
}
</style>